package com.pujiewang.gateway.filter;

import com.pujiewang.gateway.util.Assert;
import com.pujiewang.gateway.util.ConfigHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

// 请求鉴权拦截器
@Component
@Log4j2
@RequiredArgsConstructor
@SuppressWarnings("unchecked")
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private final RedisTemplate<String, String> redisTemplate;
    private final ConfigHelper configHelper;

    private final Long expireMill = 24 * 60 * 60 * 1000L;

    // 自定义线程池
    private final ExecutorService asyncExecutor = Executors.newCachedThreadPool();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();

        // 放行特殊路径
        String config = configHelper.getConfig();
        log.info("permit list: {}", config);
        if (Assert.notEmpty(config)) {
            List<String> pathList = Arrays.asList(config.split(","));
            if (Assert.notEmptyCollection(pathList)) {
                for (String configPath : pathList) {
                    if(path.startsWith(configPath)){
                        return chain.filter(exchange);
                    }
                }
            }
        }

        return chain.filter(exchange);
    }

    // 异步续期
    private void refTokenAsync(String tokenKey) {
        CompletableFuture.runAsync(() -> {
            try {
                redisTemplate.expire(tokenKey, expireMill, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                log.error("Token续期失败：", e);
            }
        }, asyncExecutor);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
